<script setup>
import { ref, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { marked } from "marked";
import { saveDraft, publishArticle } from "@/apis/blog";

const title = ref("");
const content = ref("");
const previewHtml = ref("");
const mode = ref("split"); // edit | preview | split
const saving = ref(false);
const lastSaved = ref("未保存");
const category = ref("");
const tags = ref([]);
const summary = ref("");
const cover = ref("");
const publishSetting = ref("now"); // now | schedule

watch(content, (val) => {
  previewHtml.value = marked.parse(val || "");
});

let autosaveTimer;
onMounted(() => {
  autosaveTimer = setInterval(handleSaveDraft, 10000);
});
onMounted(() => () => clearInterval(autosaveTimer));

async function handleSaveDraft() {
  if (saving.value) return;
  saving.value = true;
  try {
    await saveDraft({
      title: title.value,
      content: content.value,
      summary: summary.value,
      category: category.value,
      tags: tags.value,
      cover: cover.value,
    });
    lastSaved.value = new Date().toLocaleString();
  } catch (e) {
    // ignore
  } finally {
    saving.value = false;
  }
}

async function handlePublish() {
  if (!title.value || !content.value)
    return ElMessage.warning("请填写标题与内容");
  await publishArticle({
    title: title.value,
    content: content.value,
    summary: summary.value,
    category: category.value,
    tags: tags.value,
    cover: cover.value,
    publishSetting: publishSetting.value,
  });
  ElMessage.success("已提交发布");
}
</script>

<template>
  <div class="blog-editor blog-theme">
    <el-card shadow="never" class="editor-toolbar">
      <div class="left">
        <el-input
          class="title-input"
          v-model="title"
          placeholder="输入文章标题"
        />
      </div>
      <div class="right">
        <el-tag type="success">{{
          lastSaved === "未保存" ? "未保存" : `已保存：${lastSaved}`
        }}</el-tag>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button @click="mode = mode === 'split' ? 'edit' : 'split'"
          >编辑/分屏</el-button
        >
        <el-button @click="mode = 'preview'">预览</el-button>
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </div>
    </el-card>

    <el-row :gutter="12" class="editor-body">
      <el-col :xs="24" :md="16" v-show="mode !== 'preview'">
        <el-card shadow="never" class="editor-pane">
          <el-input
            v-model="content"
            type="textarea"
            :rows="22"
            placeholder="支持 Markdown 语法，实时预览"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8" v-show="mode !== 'edit'">
        <el-card shadow="never" class="preview-pane">
          <div class="preview" v-html="previewHtml"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="settings">
      <template #header>
        <div class="card-header">文章设置</div>
      </template>
      <el-form label-width="100px">
        <el-form-item label="分类">
          <el-select v-model="category" placeholder="选择分类">
            <el-option label="算法" value="algorithm" />
            <el-option label="后端" value="backend" />
            <el-option label="前端" value="frontend" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="输入或选择标签"
          >
            <el-option label="OJ" value="OJ" />
            <el-option label="Vue" value="Vue" />
            <el-option label="算法" value="算法" />
          </el-select>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="summary" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input
            v-model="cover"
            placeholder="图片URL（后端对接后替换为上传）"
          />
        </el-form-item>
        <el-form-item label="发布设置">
          <el-radio-group v-model="publishSetting">
            <el-radio-button label="now">立即发布</el-radio-button>
            <el-radio-button label="schedule">定时发布</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.blog-editor {
  max-width: 100%px;
  margin: 0 auto;
  margin-top: -60px;
}
.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title-input {
  width: 520px;
}
.editor-body {
  margin-top: 12px;
}
.editor-pane,
.preview-pane {
  min-height: 480px;
}
.preview {
  min-height: 420px;
}
.settings {
  margin-top: 12px;
}
@media (max-width: 768px) {
  .title-input {
    width: 100%;
  }
}
</style>
